import type {
  MessagesStatus,
  Thread,
  ThreadWithMessages,
} from "@shared/triplit/types";
import { threadsQueries } from "../definitions/threads-queries";
import type { QueryConfig, QueryOneConfig, QueryResult } from "../types";
import { useStandardQuery, useStandardQueryOne } from "./use-standard-query";

/**
 * 获取所有threads记录
 */
export function useThreads(
  config?: QueryConfig<"threads">,
): QueryResult<Thread[]> {
  return useStandardQuery(threadsQueries.all, config);
}

/**
 * 获取按创建时间倒序排列的threads
 */
export function useOrderedThreads(
  config?: QueryConfig<"threads">,
): QueryResult<Thread[]> {
  return useStandardQuery(threadsQueries.ordered, config);
}

/**
 * 获取非私有threads，按创建时间倒序
 */
export function useNonPrivateThreads(
  config?: QueryConfig<"threads">,
): QueryResult<Thread[]> {
  return useStandardQuery(threadsQueries.nonPrivateByDate, config);
}

/**
 * 获取非私有threads，按更新时间倒序
 */
export function useNonPrivateThreadsByUpdated(
  config?: QueryConfig<"threads">,
): QueryResult<Thread[]> {
  return useStandardQuery(threadsQueries.nonPrivateByUpdated, config);
}

/**
 * 根据ID获取单个thread
 */
export function useThread(
  id: string,
  config?: QueryOneConfig<"threads">,
): QueryResult<Thread | null> {
  return useStandardQueryOne(
    () => {
      if (!id) {
        return threadsQueries.byId("__nonexistent__");
      }
      return threadsQueries.byId(id);
    },
    {
      ...config,
      enabled: !!id && config?.enabled !== false,
    },
  );
}

/**
 * 根据隐私状态获取threads
 */
export function useThreadsByPrivacy(
  isPrivate: boolean,
  config?: QueryConfig<"threads">,
): QueryResult<Thread[]> {
  return useStandardQuery(() => threadsQueries.byPrivacy(isPrivate), config);
}

/**
 * 根据ID获取thread，包含messages
 */
export function useThreadWithMessages(
  id: string,
  config?: QueryOneConfig<"threads">,
): QueryResult<ThreadWithMessages | null> {
  return useStandardQueryOne(
    () => {
      if (!id) {
        return threadsQueries.byId("__nonexistent__");
      }
      return threadsQueries.withMessages(id);
    },
    {
      ...config,
      enabled: !!id && config?.enabled !== false,
    },
  ) as QueryResult<ThreadWithMessages | null>;
}

/**
 * 获取thread的最新assistant消息状态
 * @param id Thread ID
 * @param config Query configuration
 * @returns 最新assistant消息的状态，如果没有assistant消息则返回null
 */
export function useThreadWithMessagesStatus(
  id: string,
  config?: QueryOneConfig<"threads", MessagesStatus>,
): QueryResult<MessagesStatus | null> {
  return useStandardQueryOne(() => threadsQueries.withMessages(id), {
    ...config,
    enabled: !!id && config?.enabled !== false,
    select: (data) => {
      if (!data) return null;

      const messages = (data as ThreadWithMessages).messages;
      if (!messages || messages.length === 0) return null;

      const latestAssistantMessage = messages
        .filter((message) => message.role === "assistant")
        .sort((a, b) => b.orderSeq - a.orderSeq)[0];

      return latestAssistantMessage?.status || null;
    },
  });
}
